package com.xh.petdogexpert.sys.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xh.petdogexpert.base.BaseException;
import com.xh.petdogexpert.sys.dto.Menu;
import com.xh.petdogexpert.sys.mapper.MenuMapper;
import com.xh.petdogexpert.sys.service.IMenuService;


@Service
public class MenuServiceImp implements IMenuService {

	@Autowired
	MenuMapper menuMapper;
	private Logger logger = LoggerFactory.getLogger(MenuServiceImp.class);
	
	@Override
	public Menu getMenu(Menu menu) throws BaseException {
		List<Menu> menus = menuMapper.queryMenus(menu);
		if (menus.size() > 1) {
			throw new BaseException("获取多于一个菜单的数据");
		} else if (menus == null || menus.size() == 0) {
			throw new BaseException("不存在此菜单的数据");
		} else {
			return menus.get(0);
		}

	}
	
	public List<Menu> getMenus(Menu menu) {
		List<Menu> menuList = menuMapper.queryMenus(menu);
		for (int i = menuList.size() - 1; i >= 0; i--) {
			for (int j = menuList.size() - 1; j >= 0; j--) {
				Menu imenu = menuList.get(i);
				Menu jmenu = menuList.get(j);

				if (imenu.getParentId() != null && imenu.getParentId().equals(jmenu.getId())) {
					List<Menu> childrens = jmenu.getChildren() != null ? jmenu.getChildren() : new ArrayList<Menu>();
					childrens.add(imenu);
					imenu.setLevel(jmenu.getLevel() + 1);
					jmenu.setChildren(childrens);
				}
			}
		}
		menuList.removeIf((Menu m)->{
			return m.getLevel() !=0 ;
		});
		
		return menuList;
	}
	
	@Override
	public int addUpdateMenu(Menu menu) throws BaseException {
		// 校验程序
//		valudateForm.init();
//
//		valudateForm.valudate(new FormField("password", menu.getPassword()), (data) -> {
//			String password = (String) data;
//
//			if (password.length() < 8)
//				return "密码位数小于8位";
//
//			return null;
//		});
//
//		valudateForm.throwError();



		try {
			if (menu.getId() != null)
				return menuMapper.updateByPrimaryKeySelective(menu);
			else
				return menuMapper.addMenu(menu);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("新增出错");
		}

	} 

	@Override
	public int deleteMenu(Menu menu) throws BaseException {
		int count;
		try {
			count = menuMapper.deleteMenu(menu);

		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("删除失败");
		}

		return count;
	}

	@Override
	public List<Menu> queryMenus(Menu menu) {
		List<Menu> menus = menuMapper.queryMenus(menu);
		return menus;
	}
	
}
